# -*- coding: utf-8 -*-

import sys
import geojson
import json
from shapely.geometry import shape, Point
from shapely.ops import unary_union

# 设置标准输出的编码为 UTF-8
sys.stdout.reconfigure(encoding='utf-8')

def read_geojson(filename):
    """使用 json 模块来读取 GeoJSON 文件，指定 utf-8 编码"""
    with open(filename, 'r', encoding='utf-8') as file:
        return json.load(file)


def check_points_in_polygon(points_geojson, polygon_geojson):
    # 将 GeoJSON 特征转换为 Shapely 几何对象
    points = [shape(feature['geometry']) for feature in points_geojson['features']]
    polygons = [shape(feature['geometry']) for feature in polygon_geojson['features']]

    # 计算所有多边形的并集
    union_polygon = unary_union(polygons)

    # 初始化计数器和累加器
    count = 0
    total_area = 0
    total_farm_area = 0
    names_of_points = []

    # 检查每个点是否位于多边形范围内
    for i, point in enumerate(points):
        if union_polygon.contains(point):
            properties = points_geojson['features'][i]['properties']
            count += 1
            total_area += properties.get('area', 0)
            total_farm_area += properties.get('farm_area', 0)
            names_of_points.append(properties.get('name', f'Point_{i}'))

    # 返回结果
    return count, total_area, total_farm_area, names_of_points


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py <points_file> <polygon_file>")
        sys.exit(1)

    # 获取文件路径
    points_file_path = sys.argv[1]
    polygons_file_path = sys.argv[2]

    print(f"Processing points file: {points_file_path}")
    print(f"Processing polygons file: {polygons_file_path}")

    # 读取 GeoJSON 文件
    points_file = read_geojson(points_file_path)
    polygons_file = read_geojson(polygons_file_path)

    # 检查哪些点位于多边形范围内，并计算相关统计数据
    count, total_area, total_farm_area, names_of_points = check_points_in_polygon(points_file, polygons_file)

    if count > 0:
        print(f"num: {count}")
        print(f"zmj: {total_area}")
        print(f"fzarea: {total_farm_area}")
        print(f"names: {names_of_points}")
    else:
        print("没有找到位于多边形范围内的点。")